#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <gmp.h>
#include "borwein.h"

#define MAX_IT 15
#define IT_FILENAME "resultados/pth"
#define F_PREC 33219613

pthread_t callThd[3];
pthread_mutex_t yk_used, yk_ready;
pthread_mutex_t ak_used, ak_ready;


void *y_calc_thr(void* arg){
	while(1){
		calc_yk();
		pthread_mutex_lock(&yk_used);
		update_yk();
		pthread_mutex_unlock(&yk_ready);
	}
	pthread_exit(NULL);
}

void *a_calc_thr(void* arg){
	while(1){

		pthread_mutex_lock(&yk_ready);
		ak_pre_calc();
		pthread_mutex_unlock(&yk_used);

		ak_end_calc();

		pthread_mutex_lock(&ak_used);
		update_ak();
		pthread_mutex_unlock(&ak_ready);
	}

	pthread_exit(NULL);
}

void *pi_calc_thr(void* arg){
	int it = 0;

	do{
		pthread_mutex_lock(&ak_ready);
		calc_pi();
		pthread_mutex_unlock(&ak_used);

		save_it(IT_FILENAME);
	}while(check_erro() && MAX_IT > ++it);

	pthread_exit(NULL);	
}


int main (int argc, char** argv){
	unsigned int t;
	void * status;

	mpf_set_default_prec(F_PREC);

	pthread_mutex_init(&yk_used, NULL);
	pthread_mutex_init(&yk_ready, NULL);
	pthread_mutex_init(&ak_used, NULL);
	pthread_mutex_init(&ak_ready, NULL);

	t = time(NULL);	

	init_vars();
	set_init_vals();

	pthread_mutex_lock(&ak_ready);
	pthread_mutex_lock(&yk_ready);

	pthread_create(&callThd[0], NULL, pi_calc_thr, NULL);
	pthread_create(&callThd[1], NULL, a_calc_thr, NULL);
	pthread_create(&callThd[2], NULL, y_calc_thr, NULL);

	pthread_join(callThd[0], &status);
	pthread_cancel(callThd[1]);
	pthread_cancel(callThd[2]);

	printf("Tempo total %d segundos.\n", (int) time(NULL)-t);

	return EXIT_SUCCESS;
}
